﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;

namespace BuXiaChu.OrderDishes.DAFactory
{
    
    internal sealed class DataAccessCache<T>
    {
        private static Assembly dalAssembly = null;
        private static Dictionary<string, T> cacheList;
        private static readonly object lockObj = new object();
        private static readonly string dalDllPath = ConfigurationManager.AppSettings["DALDllPath"];

        static DataAccessCache()
        {
            cacheList = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
            LoadDALAssembly();
        }

        public static T GetObject(string className)
        {
            if (dalAssembly == null)
            {
                LoadDALAssembly();
            }

            className = dalDllPath + "." + className;

            var cacheKey = className;
            T classObj;
            if (!cacheList.TryGetValue(cacheKey, out classObj))
            {
                classObj = (T)dalAssembly.CreateInstance(className);
                if (classObj != null)
                {
                    cacheList.Add(cacheKey, classObj);
                }
            }

            return classObj;
        }

        private static void LoadDALAssembly()
        {
            if (dalAssembly == null)
            {
                lock (lockObj)
                {
                    if (dalAssembly == null)
                    {
                        dalAssembly = Assembly.Load(dalDllPath);
                    }
                }
            }
        }
    }
}
